package com.yaodian100.mall.member.web;

import java.math.BigDecimal;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.struts2.ServletActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;
import com.yaodian100.core.common.dao.impl.CommonCriteria;
import com.yaodian100.core.common.entity.SimplePager;
import com.yaodian100.core.common.service.DomainService;
import com.yaodian100.core.menu.entity.Menu;
import com.yaodian100.ec.member.entity.Member;
import com.yaodian100.ec.member.service.MemberService;
import com.yaodian100.ec.payment.entity.ApplyCashOut;
import com.yaodian100.ec.payment.service.TransferService;
import com.yaodian100.mall.member.util.UserData;

public class ApplyCashOutAction extends ActionSupport implements Preparable {
	private static final long serialVersionUID = -1402701108549348394L;

	/** logger */
	private final Logger logger = LoggerFactory.getLogger(ApplyCashOutAction.class); // 與 getter, setter
	private Menu cashOutTypeTypeMenu; // 與 getter, setter
	private Menu cashOutStatusMenu;
	private SimplePager pager; // 與 setter
	private Member member;
	private CommonCriteria crit;
	private DomainService<Menu> menuService;
	private TransferService transferService;
	private MemberService memberService;
	private List<ApplyCashOut> cashOutList;

	private ApplyCashOut applyCashOut;
	private String receiverName;
	private String receiverProvince;
	private String receiverCity;
	private String receiverDistrict;
	private String receiverAddress;
	private String receiverZipCode;
	private String receiverBankName;
	private String receiverBankName1;
	private String receiverBankName2;
	private String receiverBankAccountName;
	private String receiverBankAccountNumber;
	private String bankName;
	private String applyAmount;
	private BigDecimal fee;
	private String virtualBalance;
	private String pwd;
	private String actualCashOutAmount;
	private BigDecimal tempApplyAmount = new BigDecimal(0.00);
	private BigDecimal availableAmount;
	private String cashOutType;

	private String virtualBalanceResult;
	private String memberId;
	private UserData userData;

	private String err_code;

	/**
	 * 新增提现申请
	 * 
	 * @return
	 * @throws Exception
	 */
	public String add() throws Exception {
		availableAmount = getMemberData().getBalance().getVirtualBalance();
		return "edit";
	}

	BigDecimal calculateFee(BigDecimal calcApplyAmount) {
		BigDecimal tempApplyAmount = calcApplyAmount;
		BigDecimal tempFee = new BigDecimal(0.00);
		if (new BigDecimal(200).compareTo(tempApplyAmount) == 1 || new BigDecimal(200).compareTo(tempApplyAmount) == 0) {
			tempFee = new BigDecimal(2);
		} else if (new BigDecimal(200).compareTo(tempApplyAmount) == -1
				&& new BigDecimal(5000).compareTo(tempApplyAmount) == 1) {
			tempFee = new BigDecimal(applyAmount).multiply(new BigDecimal(0.01));
		} else if (new BigDecimal(5000).compareTo(tempApplyAmount) == -1) {
			tempFee = new BigDecimal(50);
		}
		return tempFee;
	}

	/**
	 * 验证提现资料
	 * 
	 * @return
	 * @throws Exception
	 */
	boolean cashOutValidate() throws Exception {
		if (cashOutType.equals("1")) {
			if (StringUtils.isBlank(receiverName) || StringUtils.length(receiverName) < 2
					|| StringUtils.length(receiverName) > 10) {
				addFieldError("receiverName", "收款人姓名不可為空值且長度須介於2~10個字元之間");
			}

			if (StringUtils.isBlank(receiverProvince)) {
				addFieldError("receiverProvince", "请选择省份/直辖市");
			}

			if (StringUtils.isBlank(receiverCity)) {
				addFieldError("receiverCity", "请选择市");
			}

			if (StringUtils.isBlank(receiverDistrict)) {
				addFieldError("receiverDistrict", "请选择县/区");
			}

			if (StringUtils.isBlank(receiverAddress)) {
				addFieldError("receiverAddress", "详细地址不可为空值");
			}

			if (StringUtils.isBlank(receiverZipCode)) {
				addFieldError("receiverZipCode", "邮递区码不可为空值");
			}
		} else {// 银行转帐
			if (StringUtils.isBlank(receiverBankAccountName) || StringUtils.length(receiverBankAccountName) < 2
					|| StringUtils.length(receiverBankAccountName) > 10) {
				addFieldError("receiverName", "开户人姓名不可為空值且長度須介於2~10個字元之間");
			}
			if (StringUtils.isBlank(receiverBankName1)) {
				addFieldError("receiverBankName1", "银行名称不可为空值");
			}
			if (StringUtils.isBlank(receiverBankName2)) {
				addFieldError("receiverBankName2", "分行名称不可为空值");
			}
			if (StringUtils.isBlank(receiverBankAccountNumber)) {
				addFieldError("receiverBankAccountNumber", "银行帐号不可为空值");
			}
		}
		if (StringUtils.isBlank(applyAmount) || !NumberUtils.isNumber(applyAmount)) {
			addFieldError("applyAmount", "提现金额不可为空值");
		}

		if (getFieldErrors().isEmpty()) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 验证会员的账户余额是否大于0及今日是否已提现过
	 * 
	 * @return
	 * @throws Exception
	 */
	public String checkVirtualBalance() throws Exception {
		member = getMemberData();
		if (null != member) {

			if (isTodayApplyCashOut()) {
				virtualBalanceResult = "每日最多只能提现1次,超过1次请改日提现";
			} else if (!hasVirtualBalance()) {
				virtualBalanceResult = "很抱歉,您目前的账户余额为￥0.00 ，无法申请提现。";
			} else {
				virtualBalanceResult = "";
			}
		}
		return "jsonVirutalBalance";
	}

	public String getActualCashOutAmount() {
		return actualCashOutAmount;
	}

	public String getApplyAmount() {
		return applyAmount;
	}

	public ApplyCashOut getApplyCashOut() {
		return applyCashOut;
	}

	public String getBankName() {
		return bankName;
	}

	public List<ApplyCashOut> getCashOutList() {
		return cashOutList;
	}

	public Menu getCashOutStatusMenu() {
		return cashOutStatusMenu;
	}

	public Menu getCashOutTypeTypeMenu() {
		return cashOutTypeTypeMenu;
	}

	public BigDecimal getFee() {
		return fee;
	}

	public Logger getLogger() {
		return logger;
	}

	public Member getMember() {
		return member;
	}

	/**
	 * 依memberId找寻会员资料
	 * 
	 * @param loginId
	 * @return
	 * @throws Exception
	 */
	Member getMemberData() throws Exception {
		member = memberService.get(userData.getMemberId());
		return member;
	}

	public String getMemberId() {
		return memberId;
	}

	public SimplePager getPager() {
		return pager;
	}

	public String getPwd() {
		return pwd;
	}

	public String getReceiverAddress() {
		return receiverAddress;
	}

	public String getReceiverCity() {
		return receiverCity;
	}

	public String getReceiverDistrict() {
		return receiverDistrict;
	}

	public String getReceiverName() {
		return receiverName;
	}

	public String getReceiverProvince() {
		return receiverProvince;
	}

	public String getReceiverZipCode() {
		return receiverZipCode;
	}

	public UserData getUserData() {
		return userData;
	}

	public String getVirtualBalance() {
		return virtualBalance;
	}

	public String getVirtualBalanceResult() {
		return virtualBalanceResult;
	}

	/**
	 * 验证帐户内的馀额是否大于0
	 * 
	 * @param memberId
	 * @return
	 * @throws Exception
	 */
	boolean hasVirtualBalance() throws Exception {
		member = getMemberData();
		if (member.getBalance().getVirtualBalance().compareTo(new BigDecimal(0)) == 1) {
			return true;
		}
		return false;
	}

	/**
	 * 验证今天是否已提现
	 * 
	 * @param memberId
	 * @return
	 * @throws Exception
	 */
	boolean isTodayApplyCashOut() throws Exception {
		// crit = new CommonCriteria();
		// crit.addEq("memberId", userData.getMemberId());
		// crit.addGe("applyDate", DateUtils.parseDate(FastDateFormat.getInstance("yyyy/MM/dd 00:00:00").format(new Date())
		// .toString(), new String[] { "yyyy/MM/dd 00:00:00" }));
		// int num = transferService.getApplyCashOutListSize(crit).intValue();
		// logger.info("= num = " + num);
		// if (num > 0)
		// return true;
		return false;
	}

	/**
	 * 帐户提现政策页
	 * 
	 * @return
	 * @throws Exception
	 */
	public String policy() throws Exception {
		member = getMemberData();
		return "policy";
	}

	public void prepare() throws Exception {
		clearErrorsAndMessages();

		if (null == cashOutTypeTypeMenu) {
			cashOutTypeTypeMenu = menuService.get("ApplyCashOut.CashOutType");
		}

		if (null == cashOutStatusMenu) {
			cashOutStatusMenu = menuService.get("ApplyCashOut.CashOutStatus");
		}

		if (null == applyCashOut) {
			applyCashOut = new ApplyCashOut();
		}

		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);
		userData = new UserData(request, response);

		logger.info("prepare ok");

	}

	/**
	 * 储存提现申请
	 * 
	 * @return
	 * @throws Exception
	 */
	public String save() {
		logger.info("== applyCashOut ==:{}", applyAmount);
		try {
			member = getMemberData();
			if (null != member) {
				if (!(cashOutValidate() && hasVirtualBalance() && !isTodayApplyCashOut())) {
					addActionMessage("提现失败");
					return "msg";
				}
				tempApplyAmount = new BigDecimal(applyAmount);
				if (member.getBalance().getVirtualBalance().compareTo(tempApplyAmount) >= 0) {
					if (cashOutType.equals("1")) {
						applyCashOut.setReceiverName(receiverName);
						applyCashOut.setReceiverCity(receiverCity);
						applyCashOut.setReceiverProvince(receiverProvince);
						applyCashOut.setReceiverDistrict(receiverDistrict);
						applyCashOut.setReceiverAddress(receiverAddress);
						applyCashOut.setReceiverZipCode(receiverZipCode);
					} else {
						applyCashOut.setReceiverBankAccountName(receiverBankAccountName);
						applyCashOut.setReceiverBankName(receiverBankName);
						applyCashOut.setReceiverBankAccountNumber(receiverBankAccountNumber);
					}
					applyCashOut.setApplyAmount(tempApplyAmount);
					applyCashOut.setFee(new BigDecimal("0"));
					applyCashOut.setActualCashOutAmount(applyCashOut.getApplyAmount().subtract(applyCashOut.getFee()));
					applyCashOut.setCashOutType(cashOutType);
					applyCashOut.setMemberId(userData.getMemberId());
					applyCashOut.setMemberName(member.getLoginId());
					applyCashOut.setCashOutStatus("10");// 处理中
					applyCashOut = transferService.saveApplyCashOut(applyCashOut);
					member = memberService.get(applyCashOut.getMemberId());
				} else {
					addActionMessage("很抱歉，你目前的账户余额不足。");
				}
			} else {
				addActionMessage("会员资料错误");
			}
		} catch (Exception e) {
			addActionMessage("提现失败");
		}
		return "msg";
	}

	public void setActualCashOutAmount(String actualCashOutAmount) {
		this.actualCashOutAmount = actualCashOutAmount;
	}

	public void setApplyAmount(String applyAmount) {
		this.applyAmount = applyAmount;
	}

	public void setApplyCashOut(ApplyCashOut applyCashOut) {
		this.applyCashOut = applyCashOut;
	}

	public void setBankName(String bankName) {
		this.bankName = bankName;
	}

	public void setCashOutList(List<ApplyCashOut> cashOutList) {
		this.cashOutList = cashOutList;
	}

	public void setCashOutStatusMenu(Menu cashOutStatusMenu) {
		this.cashOutStatusMenu = cashOutStatusMenu;
	}

	public void setCashOutTypeTypeMenu(Menu cashOutTypeTypeMenu) {
		this.cashOutTypeTypeMenu = cashOutTypeTypeMenu;
	}

	public void setCrit(CommonCriteria crit) {
		this.crit = crit;
	}

	public void setFee(BigDecimal fee) {
		this.fee = fee;
	}

	public void setMember(Member member) {
		this.member = member;
	}

	public void setMemberId(String memberId) {
		this.memberId = memberId;
	}

	public void setMemberService(MemberService memberService) {
		this.memberService = memberService;
	}

	public void setMenuService(DomainService<Menu> menuService) {
		this.menuService = menuService;
	}

	public void setPager(SimplePager pager) {
		this.pager = pager;
	}

	public void setPwd(String pwd) {
		this.pwd = pwd;
	}

	public void setReceiverAddress(String receiverAddress) {
		this.receiverAddress = receiverAddress;
	}

	public void setReceiverCity(String receiverCity) {
		this.receiverCity = receiverCity;
	}

	public void setReceiverDistrict(String receiverDistrict) {
		this.receiverDistrict = receiverDistrict;
	}

	public void setReceiverName(String receiverName) {
		this.receiverName = receiverName;
	}

	public void setReceiverProvince(String receiverProvince) {
		this.receiverProvince = receiverProvince;
	}

	public void setReceiverZipCode(String receiverZipCode) {
		this.receiverZipCode = receiverZipCode;
	}

	public void setTransferService(TransferService transferService) {
		this.transferService = transferService;
	}

	public void setUserData(UserData userData) {
		this.userData = userData;
	}

	public void setVirtualBalance(String virtualBalance) {
		this.virtualBalance = virtualBalance;
	}

	public void setVirtualBalanceResult(String virtualBalanceResult) {
		this.virtualBalanceResult = virtualBalanceResult;
	}

	/**
	 * 确认退款提现信息
	 * 
	 * @return
	 * @throws Exception
	 */
	public String view() throws Exception {
		logger.info("=== applyCashOut ===" + cashOutValidate());
		member = getMemberData();
		if (null != member) {
			if (!memberService.pwdCheck(pwd, member)) {
				err_code = "pwd_error";
				return "edit";
			}
			if (new BigDecimal(applyAmount).compareTo(member.getBalance().getVirtualBalance()) > 0) {
				addActionMessage("提现金额不得大于账户余额");
				return "msg";
			}
			if (!isTodayApplyCashOut()) {
				if (hasVirtualBalance()) {
					if (!cashOutValidate()) {
						addActionMessage("会员资料错误");
						return "msg";
					}
					tempApplyAmount = new BigDecimal(applyAmount);
					if (member.getBalance().getVirtualBalance().compareTo(tempApplyAmount) >= 0) {
						fee = new BigDecimal("0");
						actualCashOutAmount = tempApplyAmount.toString();
						virtualBalance = member.getBalance().getVirtualBalance().subtract(tempApplyAmount).toString();
					} else {
						addActionMessage("很抱歉，你目前的账户余额不足。");
						return "msg";
					}
				} else {
					addActionMessage("很抱歉，你目前的账户余额不足。");
					return "msg";
				}
			} else {
				addActionMessage("很抱歉，每日最多只能提现1次，超过1 次请改日申请。");
				return "msg";
			}
		} else {
			addActionMessage("会员资料错误");
			return "msg";
		}
		return "view";
	}

	public BigDecimal getAvailableAmount() {
		return availableAmount;
	}

	public void setAvailableAmount(BigDecimal availableAmount) {
		this.availableAmount = availableAmount;
	}

	public String getErr_code() {
		return err_code;
	}

	public void setErr_code(String errCode) {
		err_code = errCode;
	}

	public String getCashOutType() {
		return cashOutType;
	}

	public void setCashOutType(String cashOutType) {
		this.cashOutType = cashOutType;
	}

	public String getReceiverBankName() {
		return receiverBankName;
	}

	public void setReceiverBankName(String receiverBankName) {
		this.receiverBankName = receiverBankName;
	}

	public String getReceiverBankAccountName() {
		return receiverBankAccountName;
	}

	public void setReceiverBankAccountName(String receiverBankAccountName) {
		this.receiverBankAccountName = receiverBankAccountName;
	}

	public String getReceiverBankAccountNumber() {
		return receiverBankAccountNumber;
	}

	public void setReceiverBankAccountNumber(String receiverBankAccountNumber) {
		this.receiverBankAccountNumber = receiverBankAccountNumber;
	}

	public String getReceiverBankName1() {
		return receiverBankName1;
	}

	public void setReceiverBankName1(String receiverBankName1) {
		this.receiverBankName1 = receiverBankName1;
	}

	public String getReceiverBankName2() {
		return receiverBankName2;
	}

	public void setReceiverBankName2(String receiverBankName2) {
		this.receiverBankName2 = receiverBankName2;
	}
}